<?php
namespace App\Http\Controllers\Admin;

use App\Enums\ResponseEnum;
use App\Http\Controllers\AdminController;
use App\Models\Logs\ActivityLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpKernel\Exception\HttpException;

class BasicController extends AdminController
{
    public function logs(Request $request)
    {
        $model = ActivityLog::query()->where('causer_id', $this->guard()->id())->whereRaw("DATE_SUB(CURDATE(),INTERVAL 7 DAy) <= DATE(`created_at`)");
        $page = $request->get('page', 1);
        $pageSize = $request->get('limit', 10);
        $total = $model->count();
        $list = $model->offset(($page-1)*$pageSize)->limit($pageSize)->get(['log_name', 'description', 'subject_id', 'subject_type', 'created_at']);
        return $this->succeed([
            'total' => $total,
            'rows'  => $list,
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'avatar'  => 'required',
            'display_name'  => 'required|between:2,12',
        ], [
            'display_name.between' => '昵称长度为2~12个字符',
        ]);
        $data = $request->only(['avatar', 'display_name']);
        try {
            DB::transaction(function () use ($data) {
                $user = $this->guard()->user();
                if ($user && $user->update($data)) {
                    $this->CreateSyslog('管理员修改信息', $user);
                }
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function updatePassword(Request $request)
    {
        $request->validate([
            'old_password' => 'required',
            'password' => 'required|between:8,16|regex:/^[A-Za-z\d-.]+$/|confirmed',
        ], [
            'password.between' => '新密码长度8~16个字符',
            'password.regex' => '新密码不允许有空格、中文',
            'password.confirmed' => '两次输入新密码不符',
        ]);
        $password = $request->get('password');
        $oldPassword = $request->get('old_password');
        if ($password === $oldPassword) {
            throw new HttpException(ResponseEnum::BASIC_USER_OLD_PASSWORD_ERROR);
        }
        $user = $this->guard()->user();
        if ($user === null) {
            throw new HttpException(ResponseEnum::BASIC_USER_ERROR);
        }
        if (!Hash::check($oldPassword, $user['password'])) {
            throw new HttpException(ResponseEnum::BASIC_USER_PASSWORD_ERROR);
        }
        try {
            DB::transaction(function () use ($user, $password) {
                $user->update(['password' => bcrypt($password)]);
                $this->CreateSyslog('管理员修改密码', $user);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }
}
